#include "HCNetSDK.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "snapshot.h"
#include "common.h"
#include "log.h"

void print_version()
{
    uint32_t ver = NET_DVR_GetSDKVersion();
    printf("SDK Version: %d.%d.%d.%d\n", (ver >> 24) & 0xFF, (ver >> 16) & 0xFF, (ver >> 8) & 0xFF, ver & 0xFF);
}

bool capture_snapshot(char *file_name, user_camera_login_info *camera_info)
{
    long user_id, ret;
    // 初始化SDK
    NET_DVR_Init();
    NET_DVR_USER_LOGIN_INFO struLoginInfo;
    NET_DVR_DEVICEINFO_V40 struDeviceInfoV40;
    memset(&struLoginInfo, 0, sizeof(struLoginInfo));
    memset(&struDeviceInfoV40, 0, sizeof(struDeviceInfoV40));
    struLoginInfo.bUseAsynLogin = false;
    struLoginInfo.wPort = 8000;
    memcpy(struLoginInfo.sDeviceAddress, camera_info->cameraip, NET_DVR_DEV_ADDRESS_MAX_LEN);
    memcpy(struLoginInfo.sUserName, camera_info->usrname, NAME_LEN);
    memcpy(struLoginInfo.sPassword, camera_info->password, NAME_LEN);

    // 登录设备
    user_id = NET_DVR_Login_V40(&struLoginInfo, &struDeviceInfoV40);
    if (user_id < 0) {
        printf("Login failed: %d\n", NET_DVR_GetLastError());
        return false;
    }

    // 设置JPEG参数
    NET_DVR_JPEGPARA jpeg_para = {.wPicSize = 0xFF, .wPicQuality = 1};

    // 捕获快照
    ret = NET_DVR_CaptureJPEGPicture(user_id, struDeviceInfoV40.struDeviceV30.byStartChan, &jpeg_para, file_name);
    if (ret < 0) {
        printf("Capture snapshot failed: %d\n", NET_DVR_GetLastError());
        NET_DVR_Logout(user_id);
        return false;
    }
    // 登出设备
    NET_DVR_Logout_V30(user_id);
    NET_DVR_Cleanup();
    return true;
}